import { Order, OrderService, OrderStatus } from "@mallfoundry/order"
import { Button, Card, Col, Descriptions, Rate, Row, Statistic, Table, Typography } from "antd"
import { ColumnProps } from "antd/es/table"
import * as dayjs from "dayjs"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"
import { useParams } from "react-router-dom"
import Page from "../../components/page"
import { useLoading } from "../../hooks/loading"
import { useOrder } from "../../hooks/order"
import { OrderDeclineModal } from "./order-decline"
import classes from "./order-detail.module.scss"
import { OrderDiscountsModal } from "./order-discounts"
import { OrderTableItem, useOrderTableItems } from "./order-item"
import OrderShipments, { AddOrderShippingModal, EditOrderShippingModal } from "./order-shipments"
import { SourceName } from "./order-source"
import { OrderStaffNotesModal } from "./order-staff-notes"
import { OrderStatusSteps } from "./order-status"

const { Title, Text } = Typography

const {
  Incomplete,
  Pending,
  AwaitingPayment,
  AwaitingFulfillment,
  PartiallyShipped,
  Shipped,
  AwaitingPickup,
  Cancelled,
  Declined,
  Closed,
  Completed,
} = OrderStatus

interface RouterParams {
  orderId: string
}

export default function OrderDetail() {
  const { orderId = "" } = useParams<RouterParams>()
  const {
    order,
    loading: orderLoading,
    refresh: refreshOrder,
  } = useOrder(orderId)
  const [loading, setLoading] = useLoading([orderLoading])
  const { shippedTime, status = Incomplete, shippingAddress, placingExpiredTime, paymentStatus, paymentMethod } = order


  const [addShippingModalVisible, setAddShippingModalVisible] = useState(false)
  const [editShippingModalVisible, setEditShippingModalVisible] = useState(false)
  const [staffNotesModalVisible, setStaffNotesModalVisible] = useState(false)
  const [discountsModalVisible, setDiscountsModalVisible] = useState(false)
  const [cancelModalVisible, setCancelModalVisible] = useState(false)

  function handleChangeAddShippingModalVisible() {
    setAddShippingModalVisible(!addShippingModalVisible)
  }

  function handleChangeEditShippingModalVisible() {
    setEditShippingModalVisible(!editShippingModalVisible)
  }

  function handleChangeDiscountsModalVisible() {
    setDiscountsModalVisible(!discountsModalVisible)
  }

  function handleChangeCancelModalVisible() {
    setCancelModalVisible(!cancelModalVisible)
  }

  function handleChangeStaffStars(stars: number) {
    setLoading(true)
    const aOrder = new Order()
    aOrder.id = orderId
    aOrder.staffStars = stars
    OrderService.updateOrder(aOrder)
      .then(refreshOrder)
      .finally(() => setLoading(false))
  }

  const tableItems = useOrderTableItems(order)
  const orderItemsColumns: ColumnProps<OrderTableItem>[] = [
    {
      title: "商品",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "单价(元)",
      dataIndex: "price",
      key: "price",
      align: "right",
    },
    {
      title: "数量",
      dataIndex: "quantity",
      key: "quantity",
      align: "right",
    },
    {
      title: "优惠(元)",
      dataIndex: "discountTotalPrice",
      key: "discountTotalPrice",
      align: "right",
    },
    {
      title: "小计(元)",
      dataIndex: "subtotalAmount",
      key: "subtotalAmount",
      align: "right",
    },
    {
      title: "售后状态",
      dataIndex: "address",
      key: "address",
      align: "right",
      render: () => "-",
    }, {
      title: "发货状态",
      dataIndex: "shippingStatus",
      key: "shippingStatus",
      align: "right",
      render: (shippingStatus) => shippingStatus ? "已发货" : "未发货",
    },
  ]

  function renderPaymentStatus() {
    if (paymentStatus === "captured") {
      return "已支付"
    }
    return "待支付"
  }

  function renderPaymentMethod() {
    if (paymentMethod === "wxpay") {
      return "微信支付"
    }
    return "支付宝"
  }

  function onSavedStaffNotes() {
    setStaffNotesModalVisible(false)
    refreshOrder()
  }

  return (
    <div className={classes.orderDetail}>
      <Page.Header title="订单详情" ghost={false}/>
      <Page.Content loading={loading}>
        <Card>
          <Row gutter={[24, 24]}>
            <Col span={24}>
              订单号 : {order.id} 下单时间 : {order.placedTime} <SourceName source={order.source}/>
            </Col>
          </Row>
          <Row gutter={[24, 24]} className={classes.orderStatuses} align="middle">
            <Col span={10} className={classes.orderStatus}>
              {
                (_.isEqual(status, Pending) || _.isEqual(status, AwaitingPayment)) && <>
                  <Title level={4}>商品已拍下，等待买家付款</Title>
                  <Text>如买家未在
                    <Statistic.Countdown value={dayjs(placingExpiredTime).valueOf()} format="H时m分s秒"/>
                    内付款，订单将按照设置逾期自动关闭。</Text>
                  <div className={classes.orderStatusActions}>
                    <Button type="link" onClick={handleChangeDiscountsModalVisible}>改价</Button>
                    <Button type="link" onClick={handleChangeCancelModalVisible}>取消订单</Button>
                  </div>
                </>
              }
              {
                (_.isEqual(status, AwaitingFulfillment) || _.isEqual(status, PartiallyShipped)) && <>
                  <Title level={4}>等待商家发货</Title>
                  <Text>买家已付款至系统待结算账户，请尽快发货，否则买家有权申请退款。</Text>
                  <div className={classes.orderStatusActions}>
                    <Button type="primary" onClick={handleChangeAddShippingModalVisible}>发货</Button>
                  </div>
                </>
              }
              {
                (_.isEqual(status, Shipped) || _.isEqual(status, AwaitingPickup)) && <>
                  <Title level={4}>商家已发货，等待交易成功</Title>
                  <Text>买家如在<Text type="danger">7天内</Text>没有申请退款，交易将自动完成。</Text>
                  <div className={classes.orderStatusActions}>
                    <Button type="link" onClick={handleChangeEditShippingModalVisible}>修改物流</Button>
                  </div>
                </>
              }
              {
                (status === Cancelled) && <>
                  <Title level={4}>交易取消</Title>
                  <Text>{order.cancelReason}</Text>
                </>
              }
              {
                (status === Declined) && <>
                  <Title level={4}>交易取消</Title>
                  <Text>{order.declineReason}</Text>
                </>
              }
              {
                (status === Closed) && <>
                  <Title level={4}>交易关闭</Title>
                  <Text>{order.closeReason}</Text>
                </>
              }
              {
                (status === Completed) && <>
                  <Title level={4}>交易完成</Title>
                  <Text>已将货款结算至你的店铺余额账户，请注意查收。</Text>
                </>
              }
              <Row align="middle" style={{ padding: "24px 0" }}>
                <Col span={24}>
                  <Button className={classes.orderStaffNotesButton}
                          onClick={() => setStaffNotesModalVisible(true)}
                          type="link"
                          size="small">备注</Button>
                  <Rate value={order.staffStars} allowClear
                        onChange={handleChangeStaffStars}/>
                </Col>
              </Row>
            </Col>
            <Col span={14}>
              {status !== Cancelled && status !== Declined && status !== Closed
              && <>
                <OrderStatusSteps
                  status={status}
                  placedTime={order.placedTime}
                  paidTime={order.paidTime}
                  shippedTime={order.shippedTime}
                  receivedTime={order.receivedTime}/>
              </>
              }
            </Col>
          </Row>
          <Row gutter={[24, 24]} className={classes.orderNotes} align="top">
            <Col span={24}>
              {
                order.staffNotes &&
                <Descriptions>
                  <Descriptions.Item label="订单备注">
                    {order.staffNotes}
                  </Descriptions.Item>
                </Descriptions>
              }
              <Descriptions className={classes.orderTransactionAlter}>
                <Descriptions.Item label="系统提示">
                  交易成功后，系统将把货款结算至你的店铺账户余额，你可申请提现；<br/>
                  请及时关注你发出的包裹状态，确保能配送至买家手中；<br/>
                  如果买家表示未收到货或者货物有问题，请及时联系买家积极处理，友好协商；<br/>
                </Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>
          <OrderDeclineModal visible={cancelModalVisible}
                             orderId={orderId}
                             onCancel={handleChangeCancelModalVisible}
                             onDeclined={() => {
                               handleChangeCancelModalVisible()
                               refreshOrder()
                             }}/>
          <OrderDiscountsModal visible={discountsModalVisible}
                               orderId={orderId}
                               items={order.items}
                               onCancel={handleChangeDiscountsModalVisible}
                               onChanged={() => {
                                 handleChangeDiscountsModalVisible()
                                 refreshOrder()
                               }}/>
          <OrderStaffNotesModal
            visible={staffNotesModalVisible}
            orderId={orderId}
            staffNotes={order.staffNotes}
            onCancel={() => setStaffNotesModalVisible(false)}
            onSaved={onSavedStaffNotes}/>
          <AddOrderShippingModal
            visible={addShippingModalVisible && (order.status !== Shipped && order.status !== AwaitingPickup)}
            orderId={orderId}
            shippingAddress={shippingAddress}
            items={tableItems}
            onCancel={handleChangeAddShippingModalVisible}
            onShipped={refreshOrder}/>
          <EditOrderShippingModal
            visible={editShippingModalVisible}
            orderId={orderId}
            shipments={order.shipments}
            onCancel={handleChangeEditShippingModalVisible}
            onSaved={() => {
              handleChangeEditShippingModalVisible()
              refreshOrder()
            }}/>
          <OrderShipments shipments={order.shipments}/>
          <Row gutter={[24, 24]} style={{
            ...(_.isEmpty(order.shipments) ? { marginTop: "12px" } : {}),
          }}>
            <Col span={24}>
              <Row className={classes.orderShippingAddress}>
                <Col span={6}>
                  <Descriptions title="收货人信息" size="small" column={1}>
                    <Descriptions.Item label="收货人"
                                       children={`${shippingAddress?.lastName}${shippingAddress?.firstName}`}/>
                    <Descriptions.Item label="联系电话" children={shippingAddress?.phone}/>
                    <Descriptions.Item label="收货地址"
                                       children={`${shippingAddress?.province}${shippingAddress?.city}${shippingAddress?.county} ${shippingAddress?.address}`}/>
                  </Descriptions>
                </Col>
                <Col span={6}>
                  <Descriptions title="配送信息" column={1}>
                    <Descriptions.Item label="配送方式">快递</Descriptions.Item>
                    {shippedTime && <Descriptions.Item label="发货时间" children={shippedTime}/>}
                  </Descriptions>
                </Col>
                <Col span={6}>
                  <Descriptions title="支付信息" column={1}>
                    <Descriptions.Item label="支付状态" children={renderPaymentStatus()}/>
                    {order.paymentMethod && <Descriptions.Item label="支付方式" children={renderPaymentMethod()}/>}
                    {order.paidTime && <Descriptions.Item label="支付时间" children={order.paidTime}/>}
                  </Descriptions>
                </Col>
                <Col span={6}>
                  <Descriptions title="买家信息" column={1}>
                    <Descriptions.Item label="买家">15688477267</Descriptions.Item>
                    <Descriptions.Item label="买家留言">-</Descriptions.Item>
                  </Descriptions>
                </Col>
              </Row>
            </Col>
          </Row>
          <Row gutter={[24, 24]} className={classes.orderItems}>
            <Col span={24}>
              <Table rowKey="id"
                     columns={orderItemsColumns}
                     dataSource={tableItems}
                     pagination={false}/>
            </Col>
          </Row>
          <Row gutter={[24, 0]} justify="end">
            <Col span={6}>
              <Descriptions column={1} className={classes.orderPrices}>
                <Descriptions.Item label="商品总价" children={`￥${order.totalPrice}`}/>
                <Descriptions.Item label="运费" children={`￥${order.totalShippingCost}`}/>
                <Descriptions.Item label="优惠" children={`￥${order.totalDiscountTotalPrice}`}/>
                <Descriptions.Item label="运费优惠" children={`￥${order.totalDiscountShippingCost}`}/>
                <Descriptions.Item label="实收金额" className={classes.orderTotalPrice} children={`￥${order.totalAmount}`}/>
              </Descriptions>
            </Col>
          </Row>
        </Card>
      </Page.Content>
    </div>
  )
}
